package main

import "fmt"

func transpose(matrix [][]int) [][]int {
	rows := len(matrix)
	cols := len(matrix[0])

	// 方阵
	if rows == cols {
		for r := 0; r < rows; r++ {
			for c := r + 1; c < cols; c++ {
				swap(&matrix[r][c], &matrix[c][r])
			}
		}

		return matrix
	}

	// 不是方阵，需要新建一个矩阵
	// var newMatrix [cols][rows]int
	newMatrix := make([][]int, cols)

	for i := 0; i < cols; i++ {
		newMatrix[i] = make([]int, rows)
	}

	for r := 0; r < rows; r++ {
		for c := 0; c < cols; c++ {
			newMatrix[c][r] = matrix[r][c]
		}
	}

	return newMatrix
}

func swap(a *int, b *int) {
	*a, *b = *b, *a
}

func main() {
	matrix := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
	matriy := transpose(matrix)
	fmt.Println(matriy)
}
